<?php
declare (strict_types=1);

namespace app\command;

use app\data\model\ProductsCategoryFieldsRelationshipModel;
use app\data\model\ProductsCategoryModel;
use app\data\model\ProductsContentModel;
use app\data\model\ProductsFieldsModel;
use app\data\model\ProductsFieldsRelationshipModel;
use app\data\model\ProductsFilesModel;
use app\data\model\ProductsModel;
use app\model\Goods;
use app\model\GoodsCategory;
use think\console\Command;
use think\console\Input;
use think\console\Output;

class ImportProduct extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('import_product')
            ->setDescription('the import_product command');
    }

    protected function execute(Input $input, Output $output)
    {
        $limit = 10;
        $proCatModel = new ProductsCategoryModel();
        $productModel = new ProductsModel();
        $proContentModel = new ProductsContentModel();
        $proFilesModel = new ProductsFilesModel();
        $proFields = ProductsFieldsModel::select();
        $proCatModel->where(true)->delete();
        $productModel->where(true)->delete();
        $proFilesModel->where(true)->delete();
        $proContentModel->where(true)->delete();
        ProductsCategoryFieldsRelationshipModel::where(true)->delete();
        ProductsFieldsRelationshipModel::where(true)->delete();
        $output->writeln('数据已清空');
        // 首先添加产品分类
        GoodsCategory::chunk($limit, function ($cats) use ($proCatModel, $proFields, $output) {
            foreach ($cats as $cat) {
//                $catName = remoteTranslate($cat['cat_name']) ?? "";
//                $catDesc = remoteTranslate($cat['cat_desc']) ?? "";
                $catName = $cat['cat_name'];
                $catDesc = $cat['cat_desc'];
                $rewrite_url = $cat['urlrewriter'] ? 'product/' . $cat['urlrewriter'] : 'articledetail/' . $cat['cat_id'];
                $proCats = [
                    'id' => $cat['cat_id'],
                    "parent_id" => $cat['parent_id'],
//                    "name" => remoteTranslate($cat['cat_name']),
                    "name" => $catName,
                    "cover_img" => $cat['photo'],
                    "is_show" => $cat['is_show'],
                    "sort" => $cat['sort_order'],
                    "desc" => $catDesc,
                    "rewrite_url" => $rewrite_url,
                    "inner_img" => $cat['photo'],
                    "inner_content" => $catDesc,
                    "ver" => 0,
                    "create_time" => time(),
                    "update_time" => time(),
                    "delete_time" => 0,
                ];
                $cat_id = $proCatModel->insertGetId($proCats);
                $proCatModel->find($cat_id)->relationFields()->saveAll($proFields);
                updateRoute(
                    $proCats['name'],
                    '/index/page/product',
                    $rewrite_url,
                    $rewrite_url,
                    ['id' => $proCats['id']],
                    'product'
                );
                $output->writeln("产品分类：" . $cat['cat_name'] . ',添加成功');
            }
        });
        // 其次添加产品

        Goods::with([
            "getDetails",
            "getGallery",
        ])->chunk($limit, function ($_goods) use (
            $productModel, $output, $proContentModel,
            $proFilesModel
        ) {
            foreach ($_goods as $good) {
                $goods_name = $good['goods_name'];
                $rewrite_url = $good['urlrewriter'] ? 'productdetail/' . $good['urlrewriter'] : 'productdetail/' . $good['goods_id'];

                // 添加产品
                $product = [
                    "product_id" => $good['goods_id'],
                    "title" => $good['goods_sn'],
                    "name" => $goods_name,
                    "pdt_desc" => $good['goods_ms'],
                    "delete_time" => 0,
                    "create_time" => time(),
                    "update_time" => time(),
                    "ver" => 0,
                    "cate_id" => $good['cat_id'],
                    "is_show" => $good['is_on_sale'],
                    "is_hot" => $good['is_hot'],
                    "sort" => $good['sort_order'] ?? 0,
                    "cover_img" => $good['photo'],
                    "seo_title" => $good['pagetitle'] ?? $goods_name,
                    "seo_keywords" => $good['pagekeywords'] ?? $goods_name,
                    "seo_desc" => $good['pagedesc'] ?? $goods_name,
                    "content" => $good['goods_desc'],
                    "argument" => "",
                    "accessory" => "",
                    "rewrite_url" => $rewrite_url,
                    "attachment" => $good['filename'] ?? "",
                ];
                $proId = $productModel->insertGetId($product);
                if ($proId) $output->writeln('产品：' . $product['name'] . ',添加成功');
                $output->writeln(gettype($product['name']));

                updateRoute(
                    $product['name'],
                    '/index/page/productDetail',
                    strval($rewrite_url),
                    strval($rewrite_url),
                    ['id' => $proId],
                    'product'
                );
                if ($proId) $output->writeln('产品路由：' . $product['name'] . ',添加成功');
                $pro = $productModel->find($proId);
                // 添加拓展字段
                $proFields = [
                    [
                        'id' => 1,
                        'value' => $good['goods_number'],
                    ],
                    [
                        'id' => 2,
                        'value' => $good['warn_number'],
                    ],
                    [
                        'id' => 3,
                        'value' => $good['weight_unit'],
                    ],
                    [
                        'id' => 4,
                        'value' => $good['goods_video'],
                    ],
                ];
                $pro->productExtFields()->detach();
                foreach ($proFields as $proField) {
                    $pro->productExtFields()->attach($proField['id'], ['value' => $proField['value'] ?? ""]);
                }
                $output->writeln('产品：' . $product['name'] . ',添加拓展字段成功');
                // 添加详情内容
                $details = $good['getDetails'];
                $argument = '';
                foreach ($details as $detail) {
                    $proContentModel->insertGetId([
                        "name" => $detail['details_name'],
                        "en_name" => $detail['details_name'],
                        "type_id" => $detail['type'],
                        "content" => $detail['details'],
                        "rewrite_url" => "",
                        "sort" => $detail['order_id'] ?? 0,
                        "is_show" => 1,
                        'product_id' => $proId,
                        "ver" => 0,
                        "create_time" => time(),
                        "update_time" => time(),
                        "delete_time" => 0,
                    ]);
                    $argument .= $detail['details'];
                }
                $productModel->update(['argument' => $argument], ['product_id' => $proId]);

                // 添加相册
                $gallerys = $good['getGallery'];
                foreach ($gallerys as $gallery) {
                    $proFilesModel->insertGetId([
                        "name" => $gallery['title'],
                        "link" => $gallery['original_img'],
                        "download_count" => 0,
                        "is_show" => 1,
                        "sort" => $gallery['order_id'],
                        'type_id' => 0,
                        'product_id' => $proId,
                        "ver" => 0,
                        "create_time" => time(),
                        "update_time" => time(),
                        "delete_time" => 0,
                    ]);
                }
                $output->writeln('产品：' . $product['name'] . ',添加相册成功');
            }
        });
        $output->writeln('结束产品导入');
    }
}
